package com.graduation.springbootinit.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.graduation.springbootinit.common.ErrorCode;
import com.graduation.springbootinit.exception.BusinessException;
import com.graduation.springbootinit.mapper.CulturePartCommentMapper;
import com.graduation.springbootinit.model.entity.CulturePart.CulturePartComment;
import com.graduation.springbootinit.service.CulturePartCommentService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class CulturePartCommentServiceImpl implements CulturePartCommentService {

    @Resource
    private CulturePartCommentMapper commentMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addComment(CulturePartComment comment) {
        // 验证评论内容
        if (comment.getContent() == null || comment.getContent().trim().isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "评论内容不能为空");
        }

        // 如果是回复评论，验证父评论是否存在
        if (comment.getParentId() != null) {
            CulturePartComment parentComment = commentMapper.selectById(comment.getParentId());
            if (parentComment == null) {
                throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "父评论不存在");
            }
            // 设置文章ID与父评论一致
            comment.setDiscussionId(parentComment.getDiscussionId());
        }

        // 初始化评论
        comment.setLikeCount(0);
        comment.setCreateTime(new Date());
        comment.setUpdateTime(new Date());
        commentMapper.insert(comment);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteComment(Long id) {
        // 删除评论及其所有回复
        commentMapper.delete(new QueryWrapper<CulturePartComment>()
                .eq("id", id)
                .or()
                .eq("parent_id", id));
    }

    @Override
    public void updateComment(CulturePartComment comment) {
        // 验证评论是否存在
        CulturePartComment existingComment = commentMapper.selectById(comment.getId());
        if (existingComment == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "评论不存在");
        }

        // 验证评论内容
        if (comment.getContent() == null || comment.getContent().trim().isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "评论内容不能为空");
        }

        // 更新评论
        comment.setUpdateTime(new Date());
        commentMapper.updateById(comment);
    }

    @Override
    public List<CulturePartComment> getCommentsByDiscussionId(Long discussionId) {
        // 获取文章的所有一级评论（parent_id为null的评论）
        QueryWrapper<CulturePartComment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("discussion_id", discussionId)
                .isNull("parent_id")
                .orderByDesc("create_time");
        return commentMapper.selectList(queryWrapper);
    }

    @Override
    public List<CulturePartComment> getCommentReplies(Long commentId) {
        // 获取评论的所有回复
        QueryWrapper<CulturePartComment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", commentId)
                .orderByAsc("create_time");
        return commentMapper.selectList(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void likeComment(Long commentId) {
        // 验证评论是否存在
        CulturePartComment comment = commentMapper.selectById(commentId);
        if (comment == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "评论不存在");
        }
        // 增加点赞数
        comment.setLikeCount(comment.getLikeCount() + 1);
        comment.setUpdateTime(new Date());
        commentMapper.updateById(comment);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void unlikeComment(Long commentId) {
        // 验证评论是否存在
        CulturePartComment comment = commentMapper.selectById(commentId);
        if (comment == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "评论不存在");
        }
        // 减少点赞数，确保不会小于0
        comment.setLikeCount(Math.max(0, comment.getLikeCount() - 1));
        comment.setUpdateTime(new Date());
        commentMapper.updateById(comment);
    }

    @Override
    public String getCommentInfo(Long commentId) {
        // 验证评论是否存在
        CulturePartComment comment = commentMapper.selectById(commentId);
        if (comment == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "评论不存在");
        }
        // 返回指定格式的评论信息
        return comment.getUserName() + "：" + comment.getContent();
    }
}